package com.dongzili.common.mybatisjoin;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.github.yulichang.base.MPJBaseMapper;
import com.github.yulichang.base.MPJBaseService;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;

import java.util.concurrent.ConcurrentHashMap;

public class MPJMapperUtil {
    /**
     * 服务缓存
     */
    private static final ConcurrentHashMap<Class<?>, MPJBaseService<?>> SERVICE_CACHE = new ConcurrentHashMap<>();

    /**
     * Mapper缓存
     */
    private static final ConcurrentHashMap<Class<?>, MPJBaseMapper<?>> MAPPER_CACHE = new ConcurrentHashMap<>();

    /**
     * 获取Service（带缓存）
     */
    @SuppressWarnings("unchecked")
    public static <T> MPJBaseService<T> getService(final Class<T> t) {
        try {
            DS ds = t.getAnnotation(DS.class);
            if (ds != null){
                DynamicDataSourceContextHolder.push(ds.value());
            }else{
                DynamicDataSourceContextHolder.push("main");
            }
            return (MPJBaseService<T>) SERVICE_CACHE.computeIfAbsent(t, k -> {
                String beanName = getBeanName(t, "MPJServiceImpl");
                return SpringUtil.getBean(beanName);
            });
        } catch (NoSuchBeanDefinitionException e) {
            throw new RuntimeException("未找到对应的Service实现: " + getBeanName(t) + "MPJServiceImpl", e);
        }
    }

    /**
     * 获取deep Service（带缓存）
     */
    @SuppressWarnings("unchecked")
    public static <T> MyMPJDeepService<T> getDeepService(final Class<T> t) {
        try {
            DS ds = t.getAnnotation(DS.class);
            if (ds != null){
                DynamicDataSourceContextHolder.push(ds.value());
            }else{
                DynamicDataSourceContextHolder.push("main");
            }
            return (MyMPJDeepService<T>) SERVICE_CACHE.computeIfAbsent(t, k -> {
                String beanName = getBeanName(t, "MPJDeepServiceImpl");
                return SpringUtil.getBean(beanName);
            });
        } catch (NoSuchBeanDefinitionException e) {
            throw new RuntimeException("未找到对应的Service实现: " + getBeanName(t) + "MPJDeepServiceImpl", e);
        }
    }

    /**
     * 获取Mapper（带缓存）
     */
    @SuppressWarnings("unchecked")
    public static <T> MPJBaseMapper<T> getMapper(final Class<T> t) {
        try {
            DS ds = t.getAnnotation(DS.class);
            if (ds != null){
                DynamicDataSourceContextHolder.push(ds.value());
            }else{
                DynamicDataSourceContextHolder.push("main");
            }
            return (MPJBaseMapper<T>) MAPPER_CACHE.computeIfAbsent(t, k -> {
                String beanName = getBeanName(t, "MPJMapper");
                return SpringUtil.getBean(beanName);
            });
        } catch (NoSuchBeanDefinitionException e) {
            throw new RuntimeException("未找到对应的Mapper: " + getBeanName(t) + "MPJMapper", e);
        }
    }

    /**
     * 获取bean名称
     */
    private static <T> String getBeanName(final Class<T> t) {
        return t.getSimpleName().substring(0, 1).toLowerCase() + t.getSimpleName().substring(1);
    }

    private static <T> String getBeanName(final Class<T> t, String type){
        return getBeanName(t)+type;
    }
//    private static <T> String getBeanName(final Class<T> t,BeanType type){
//        String packageName = PackagePathProcessor.getParentPackageName(t);
//        if (type == BeanType.MPJServiceImpl){
//            return packageName + ".service" + "." + t.getSimpleName() + "MPJServiceImpl";
//        } else if (type == BeanType.MPJDeepServiceImpl){
//            return packageName + ".service" + "." + t.getSimpleName() + "MPJDeepServiceImpl";
//        } else if (type == BeanType.MPJMapper){
//            return packageName + ".mapper" + "." + t.getSimpleName() + "MPJMapper";
//        }else{
//            throw new RuntimeException("未知的BeanType");
//        }
//    }


}